<template>
	<view class="audio-box">
		<!-- @click="recordedEvent()" @tap="playRecord"-->
		<div class="recorded-btn"  @click="recordedEvent()">
			 <image src="../../../static/ic_record@2x.png" ></image>
		</div>
		<div class="audio-shaden" v-if="isShaden">
			<div class="audio-bottom">
				<div class="audio-shaden-title">
					 <div> <image @click="closedEvent()" src="../../../static/ic_close@2x.png" ></image></div>
					 <text  :style="{color:isFlag?'#333333':'#9A9B9D'}">
						{{isFlag? formatTime(totalTime) :'最长可录制'+topTime(question.audioMax)}}
					 </text>
					 <span :style="{color:isSucceed?'#fff':'#999999',backgroundColor:isSucceed?'#FD453D':'#F6F8FC'}" @click="submitEvent">发布</span>
				</div>
				<!--  -->
				<div class="countDown" v-if="countdown!=0">
					{{countdown}}
				</div>
				<div class="onRecording" v-if="isRecording" >
					<div class="tapEvent" @tap="stopRecord(null)"></div>
					<image src="../../../static/ysplay.gif" class="pause-imggif"></image>
				</div>
				<div class="onRecording"  v-if="isSucceed">
					<span @tap="playRecord" v-if="!isPlaying">
						<image src="../../../static/ic_pause.png" class="pause-img"></image>
					</span>
					<span @tap="pauseAudio" v-if="isPlaying" >
						<image src="../../../static/ic_play.png" class="pause-img"></image>
					</span>
				</div>
			</div>
		</div>
		<div class="autoDialog" v-if="isAutoDialog">
			<autoDialogDefault :btnText="isAutoDialogData.btnText" :btnColseText='isAutoDialogData.btnColseText' :closeIcon="closeIcon2" :content="isAutoDialogData.text" title="温馨提示" style="width:100%" @ok="nullitBtn(isAutoDialogData.btnText)" @closeBtn='closeBtn'></autoDialogDefault>
		</div>
	</view>
</template>

<script>
	import autoDialogDefault from './auto-dialog/auto-dialog-default.vue';
	 import {apiSpeakingUpload } from '@/api/exam/exam.js'
	export default {
		props:{
			question:{
				type:Object,
				default:()=> ({})
			}
		},
		components:{
			autoDialogDefault
		},
		data() {
			return {
				isFlag:false, //弹框顶部文案控制 展示时间还是文案
				isShaden:false,
				countdown:3,//33秒开始录音倒计时
				interval:null,
				totalTime: 10, // 初始倒计时时间，单位为秒
				totalTimeinterval:null,
				isAutoDialog:false,//提示开关
				isAutoDialogData:{ //提示文案
					text:null,
					btnText:null ,
					btnColseText:null
				},
				
				recorder: null,
				isRecording: false, //是否正在录音
				audioCtx: null,
				isSucceed:false,// 录音结束 控制发布按钮
				durationTime:'',//音频时长
				isPlaying:false,//是否在播放中
				
				tempFilePath:'',//非七牛云的录音地址
				dataDuration:0//录音时长

			}
		},
		mounted() {
			// this.totalTime=this.question.audioMax
		},
		beforeDestroy() {
			console.log('录音组件销毁')
			this.stopRecord(null)
			this.initData()
		},
		methods: {
			// 发布按钮
			submitEvent(){
				if(this.isSucceed){
					// 上传七牛云1
					this.interface(this.tempFilePath)
					this.audioCtx.stop();
				}
				
			},
			// 3秒倒计时开始录音
			 startCountdown() {
				 // 获取最长可录制时间
				 this.totalTime=this.question.audioMax
				 
				 if(this.countdown>0){
					 this.interval = setInterval(() => {
					   const countdown = this.countdown-1
					   this.countdown = countdown;
					 					// 判断 3秒倒计时录音是否为0
					   if (countdown <= 0) {
					     clearInterval(this.interval); // 清除定时器
						  this.interval=null
						  
						  this.isFlag=true
						  console.log('3秒倒计时结束');
						  // 录音总时长倒计时
						  this.totalTimeCountdown()
						  // 开始录音
						  this.startRecord()
					   }
					 }, 1000); // 每秒更新一次倒计时
				 }
	
			},
			// 判断音频权限是否开启 
			recordedEvent(){
				this.$tip.loading()
				this.$bus.$emit("send",true)
				  uni.getSetting({
				    success: (res) => {
				      // 判断麦克风权限是否已经授权
				      if (res.authSetting['scope.record']) {
						  this.$tip.loaded()
						// 开始 打开3秒倒计时录音弹框
						this.isShaden=true
						this.startCountdown()
				        console.log('麦克风权限已授权');
				      } else {
				        console.log('麦克风权限未授权');
				        // 提示用户去设置页面开启权限
				        uni.showModal({
				          title: '申请麦克风权限',
				          content: '您还未开启麦克风权限，是否前往设置页面开启？',
				          success: (res) => {
							   this.$tip.loaded()
				            if (res.confirm) {
								uni.authorize({
									scope: 'scope.record',
				             // uni.openSetting({
								 success: (res) => {
								   if (res.authSetting['scope.record']) {
									 this.$tip.loaded()
									 console.log('用户已授权麦克风权限');
									 // 开始 打开3秒倒计时录音弹框
									 this.isShaden=true
									 this.startCountdown()
								   }
								 }
							 }); // 打开设置页面
				            } else if (res.cancel) {
								 this.$tip.loaded()
				              console.log('用户点击取消');
				            }
				          },
				        });
				      }
				    },
				    fail: (err) => {
						 this.$tip.loaded()
				      console.error('获取设置失败', err);
				    }
				  });

			},
			// 关闭
			closedEvent(){
				// 是否录音完成
				if(this.isSucceed){
					this.isAutoDialog=true
					this.isAutoDialogData={
						text:'关闭后录音将不会保存<br/>确定退出录音吗',
						btnText:"继续作答" ,
						btnColseText:'退出'
					}
				}else{
					this.initData()
					this.isShaden=false
				}
				
			},
			// 录音时长倒计时
			totalTimeCountdown() {
			      this.totalTimeinterval = setInterval(() => {
			        const totalTime = this.totalTime - 1;
			        this.totalTime = totalTime;
			
			        if (totalTime <= 0) {
			          clearInterval(this.totalTimeinterval); // 清除定时器
					  this.totalTimeinterval=null
			          console.log('录音倒计时结束',this.isRecording);
					  // isRecording 为真说明是在录音 
					  if(this.isRecording){
						  // 停止录音
						  this.stopRecord(this.question.audioMax)
					  }else{
						  // 设为播放录音文案 按钮
						  this.isPlaying=false
					  }
					 
			        }
			      }, 1000); // 每秒更新一次倒计时
			},

			//二次确认弹框  确认继续作答
			nullitBtn(text){
				console.log('重新作答？',text)
				this.isAutoDialog=false //关闭二次提示弹框
				if(text=='重新作答'){
					this.initData()
					this.startCountdown()
				}
			},
			// 二次确认弹框   退出关闭
			closeBtn(){
				// 停止
				this.stopRecord(null)
				this.initData()
				this.isShaden=false
				this.isAutoDialog=false
			},
			// 开始录音
			startRecord() {
			      if (this.isRecording) {
			        uni.showToast({
			          title: '正在录音中，请勿重复操作',
			          icon: 'none'
			        });
			        return;
			      }
			
			      this.isRecording = true;
			      this.recorder = uni.getRecorderManager();
				  this.recorder.start({
						duration:600000, 			//指定录音的时长，单位 ms
						// sampleRate: 16000, 			//采样率        44100,
						// numberOfChannels: 1, 		//录音通道数 
						// encodeBitRate: 96000, 		//编码码率   192000
						format: 'mp3', 				//音频格式，有效值 aac/mp3 
						// frameSize: 10, 				//指定帧大小，单位 KB   50
				  });
			      this.recorder.onStart(() => {
			        console.log('开始录音');
			      });
			
			},
			// 录音结束
			stopRecord(dateNum) {
				this.totalTime=0
				clearInterval(this.totalTimeinterval); // 清除定时器
				this.totalTimeinterval=null
				if (!this.isRecording) {
					return;
				}
				this.$tip.loading()
				this.recorder.stop();
				this.recorder.onStop((res) => {
					console.log('录音时长',Math.floor(res.duration))
					this.$tip.loaded()
					// 停止录音的一个状态
					this.isRecording = false;
					// 开始播放按钮显示
					this.isPlaying=false
					
					this.isSucceed=true
					if(Math.floor(res.duration/1000)<this.question.audioMin){
						console.log('这是录音过短')
						this.$tip.loaded()
						this.isAutoDialog=true
					
						this.isAutoDialogData={
							text:'您的作答时间低于'+this.question.audioMin+'秒<br/>请重新作答',
							btnText:"重新作答",
							btnColseText:'放弃'
						}
						return
					}
				
					this.dataDuration=dateNum||Math.floor(res.duration/1000)
			
					// 录制时间
					this.totalTime = this.dataDuration
					this.$tip.loaded()
						
					this.tempFilePath=res.tempFilePath
					this.audioCtx = uni.createInnerAudioContext();
					this.audioCtx.sessionCategory = 'soloAmbient';//在后台时不播放，如有其他播放，会暂停其他播放（但在移动端h5中 后台不播放失效）
					this.audioCtx.src = res.tempFilePath;
				});
			},
			// 播放录音
			playRecord() {
				// this.totalTime=0
				console.log('res.tempFilePath',this.audioCtx,this.tempFilePath)
			  if (this.audioCtx) {
				// 播放录音
				   this.audioCtx.play();
				   this.isPlaying=true //正在播放
				   this.audioCtx.onCanplay(() => {
							this.durationTime = Math.floor(this.audioCtx.duration);
				   });
				  
				 
				   // 如果有时间 就不再继续获取时间了  代表上次暂停播放了 这次继续播放
				   if(this.totalTime){
					   this.totalTimeCountdown()
					   return
				   }
				   
				   let flag=true
				  //  // 获取录音 音频时长
				   this.audioCtx.onTimeUpdate(() => {
					  if(flag){
						  flag=false
						  this.totalTime = Math.floor(this.audioCtx.duration)
						  this.totalTimeCountdown()
						  console.log('音频时长',Math.floor(this.audioCtx.duration))
					  } 
				  })
					
			  } else {
				uni.showToast({
				  title: '请先录音并停止录音后再播放',
				  icon: 'none'
				});
			  }
			},
			//暂停
			pauseAudio() {
			    this.audioCtx.pause();
				this.isPlaying=false
				
				clearInterval(this.totalTimeinterval); // 清除定时器
				this.totalTimeinterval=null
			},
			// 提交口语音频接口
			speakingUpload(src){
				return new Promise((resolve, reject) => {
					apiSpeakingUpload({
						topicId:JSON.stringify(this.question.id),
						audioTime:this.dataDuration,
						url:src
					}).then(res=>{
						console.log('提交口语音频',res)
						if(res.code==200){
							this.initData()
							this.isShaden=false
							this.$emit('submitRecord',true)
							resolve()
						}else{
							this.$tip.confirm(res.msg, false)
						}
						
					}).catch(err=>{
						this.$tip.confirm(err.msg, false)
						reject()
					})
				})
			},
			// 上传七牛云 --已修改为新上传地址 阿里云
			interface(filePathURL){
				this.$tip.loading()
				let url = ''
				let Authorization = uni.getStorageSync('Access-Token')
				if(process.env.NODE_ENV == 'development'){
					url = "https://bjielts-t.test.xdf.cn/test-api/answer/ielts/uploadAudioFile"
				} else {
					url = "https://bjielts.xdf.cn/prod-api/answer/ielts/uploadAudioFile"
				}
				uni.uploadFile({
					url: url,
					filePath: filePathURL,
					name: 'file',
					header: {
						u2at: Authorization
					},
					complete:(res) => {
						let data = JSON.parse(res.data)
						if(data.code == 200){
							this.speakingUpload(data.data).then(res=>{
								this.$tip.loaded()
							}).catch(err=>{
								this.$tip.loaded()
								uni.showToast({
									icon: 'none',
									title: err.errMsg
								});
							})
						}else {
							this.$tip.toast(data.msg)
						}
					},
					fail:(err)=>{
						this.$tip.loaded()
						uni.showToast({
							icon: 'none',
							title: err
						});
					}
				})
			},
			// 时间格式 倒计时
			formatTime(time) {
			  const minutes = Math.floor(time / 60);
			  const seconds = time % 60;
			  return 0+`${minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
			},
			// 时间格式 倒计时
			topTime(time) {
			  const minutes = Math.floor(time / 60);
			  const seconds = time % 60;
	 
			  if(minutes&&!seconds){
				  return minutes+'分钟'
			  }else if(minutes&&seconds){
				   return minutes+'分'+seconds+'秒'
			  }else if(!minutes&&seconds){
				  return seconds+'秒'
			  }
			
			},
			//重置
			initData(){

				this.recorder= null
				this.audioCtx= null
				this.isFlag=false  //弹框顶部 显示文案 还是时间
				
				this.countdown=3  //3秒倒计时 时间
				clearInterval(this.interval) //清除3秒倒计时 开始录音
				this.interval=null	//清除3秒倒计时 开始录音
				
				this.totalTime=this.question.audioMax	//录音总时长 秒
				clearInterval(this.totalTimeinterval); //清除录音倒计时
				this.totalTimeinterval=null //清除录音倒计时
				
				this.isRecording = false; //是否正在录音
				this.isSucceed=false//录音结束 控制是否发布的  
				
				this.isPlaying=false //是否在播放
				this.tempFilePath=''//录音的地址 非七牛云地址
			},
		}
	}
</script>

<style scoped lang="scss">
    @function torem($rpx){  //$rpx为需要转换的字号
        @return #{$rpx * 100 / 750 / 4}rem; 
    }
	.audio-box{
		// background-color: #f0f;
	}
	.recorded-btn{
		display: flex;
		align-items: center;
		justify-content: center;
		image{
			width: torem(121);
			height: torem(121);
			
		}
	}
	.audio-shaden{
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height:100%;
		z-index: 99;
		background-color: rgba(0, 0, 0, .6);
		display: flex;
		align-items: flex-end;
		.audio-bottom{
			width: 100%;
			background-color: #ffffff;
			height: torem(420);
			border-top-left-radius: torem(20);
			border-top-right-radius: torem(20);
			padding: torem(40) torem(30) torem(30);
			box-sizing: border-box;
			display: flex;
			flex-direction: column;
			.audio-shaden-title{
				display: flex;
				justify-content: space-between;
				align-items: center;
			
				font-size: torem(28);
				color: #9A9B9D;
				
				div{
					width: torem(98);
					image{
						width: torem(25);
						height: torem(25);
					}
				}
				span{
					display: flex;
					background-color: #F6F8FC;
					width: torem(98);
					height: torem(48);
					border-radius: torem(30);
					font-size: torem(24);
					justify-content: center;
					align-items: center;
				}
			}
			.onRecording{
				flex: 1;
				font-size: torem(80);
				color: #FD453D;
				font-weight: bold;
				display: flex;
				justify-content: center;
				align-items: center;
				position: relative;
				.pause-img{
					width: torem(130);
					height: torem(130);
				}
				.tapEvent{
					position: absolute;
					left: 50%;
					margin-left: torem(-65);
					width: torem(130);
					height: torem(130);
				}
				.pause-imggif{
					width: torem(418);
					height: torem(137);
				}
			}
			.countDown{
				flex: 1;
				font-size: torem(80);
				color: #FD453D;
				font-weight: bold;
				display: flex;
				justify-content: center;
				align-items: center;
				
			    animation-name: likes;     // 动画名称
				animation-direction: normal;   // 动画在奇数次（1、3、5...）正向播放，在偶数次（2、4、6...）反向播放。
				animation-timing-function: linear;    // 动画执行方式，linear：匀速；ease：先慢再快后慢；ease-in：由慢速开始；ease-out：由慢速结束；ease-in-out：由慢速开始和结束；
				animation-delay: 0s;    // 动画延迟时间
				animation-iteration-count: 3;    //  动画播放次数，infinite：一直播放
				animation-duration: 1.1s;   // 动画完成时间
			}
			@keyframes likes {
				0% {
					-webkit-transform: scale(1);
					// opacity: 0
				}
				100% {
					-webkit-transform: scale(0);
					// opacity: 1
				}
			}
			
		}
	}
.autoDialog{
	position: fixed;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, .5);
	top: 0;
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 100;
}
</style>
